package com.project.myxima;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.project.myxima.adapters.PlayerTrackPagerAdapter;
import com.project.myxima.base.BaseActivity;
import com.project.myxima.interfaces.IPlayerCallback;
import com.project.myxima.presenters.PlayerPresenter;
import com.project.myxima.utils.Constants;
import com.project.myxima.utils.LogUtils;

import com.project.myxima.views.PlayList_PopupWindow;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_LIST;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_RANDOM;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE_LOOP;

public class PlayerActivity extends BaseActivity implements IPlayerCallback, ViewPager.OnPageChangeListener {

    private static final String TAG = "PlayerActivity";
    private static final long BG_DURATION = 500;
    private ImageView mControlBtn;
    private PlayerPresenter mPlayerPresenter;
    private SimpleDateFormat mMinFormat = new SimpleDateFormat("mm:ss");
    private SimpleDateFormat mHourFormat = new SimpleDateFormat("hh:mm:ss");
    private TextView mDuration;
    private TextView mCurrentPos;
    private SeekBar mDurationBar;
    private int mCurrentProgress;
    private boolean mIsUserTouchProgressBar = false;
    private ImageView mPlayPreBtn;
    private ImageView mPlayNextBtn;
    private TextView mTrackTitleTv;
    private String mTrackTitleText;
    private ViewPager mTrackPageView;
    private PlayerTrackPagerAdapter mPlayerTrackPagerAdapter;
    private boolean mIsUserSlidePager = false;
    private ImageView mPlayModeSwitchBtn;
    private static Map<XmPlayListControl.PlayMode, XmPlayListControl.PlayMode> sPlayModeRule = new HashMap<>();
    private XmPlayListControl.PlayMode mCurrentPlayMode = PLAY_MODEL_LIST;

    static {
        sPlayModeRule.put(PLAY_MODEL_LIST,PLAY_MODEL_LIST_LOOP);
        sPlayModeRule.put(PLAY_MODEL_LIST_LOOP,PLAY_MODEL_RANDOM);
        sPlayModeRule.put(PLAY_MODEL_RANDOM,PLAY_MODEL_SINGLE_LOOP);
        sPlayModeRule.put(PLAY_MODEL_SINGLE_LOOP,PLAY_MODEL_LIST);
    }

    private View mPlayListBtn;
    private PlayList_PopupWindow mPopupWindow;
    private ValueAnimator mOutValueAnimator;
    private ValueAnimator mEnterAnimator;
    private ValueAnimator mExitAnimator;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);

        initView();
        //界面初始化后才去获取列表，获取到列表后会给适配器设置数据
        //TODO：BUG初次点击no.i条声音时，图片是第0张(Bug here)，拖动到下一张照片时变成i+1 张，但是标题and content是对的
        initPresenter();

        initEvent();
        //startPlay();//设置图片、列表数据的逻辑不在这里，在getPlayList和注册回调那里

        initAnimator();
    }

    private void initPresenter() {
        mPlayerPresenter = PlayerPresenter.getPlayerPresenter();
        mPlayerPresenter.registerViewCallback(this);
        mPlayerPresenter.getPlayList();

    }

    private void initAnimator() {
        mEnterAnimator = ValueAnimator.ofFloat(1.0f, 0.6f);
        mEnterAnimator.setDuration(BG_DURATION);
        mEnterAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float alpha = (float) animation.getAnimatedValue();
                updateBGAlpha(alpha);
            }
        });

        mExitAnimator = ValueAnimator.ofFloat(0.6f, 1.0f);
        mExitAnimator.setDuration(BG_DURATION);
        mExitAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float alpha = (float) animation.getAnimatedValue();
                updateBGAlpha(alpha);
            }
        });
    }

    private void startPlay() {
        if (mPlayerPresenter != null) {
            mPlayerPresenter.play();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPlayerPresenter != null) {
            mPlayerPresenter.unregisterViewCallback(this);
            mPlayerPresenter = null;
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initEvent() {
        mControlBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //根据当前播放状态决定点击事件
                if (mPlayerPresenter.isPlaying()) {
                    mPlayerPresenter.pause();
                }else {
                    mPlayerPresenter.play();
                }
            }
        });

        //拖动进度条
        mDurationBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean isFromUser) {
                if(isFromUser){//如果是用户触发的
                    mCurrentProgress = progress;
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                mIsUserTouchProgressBar = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {//当用户的手指离开时，更新播放进度
                mIsUserTouchProgressBar = false;
                mPlayerPresenter.seekTo(mCurrentProgress);
            }
        });

        //切换上下首
        mPlayPreBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.playPre();
                }

            }
        });

        mPlayNextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mPlayerPresenter != null){
                    mPlayerPresenter.playNext();
                }
            }
        });

        //切换图片时切换播放节目
        mTrackPageView.addOnPageChangeListener(this);

        mTrackPageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                int action = motionEvent.getAction();
                switch (action){
                    case MotionEvent.ACTION_DOWN:
                        mIsUserSlidePager = true;
                        break;
                }
                return false;
            }
        });

        //切换播放模式
        mPlayModeSwitchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //根据当前mode，切换到下一个mode
                switchPlayMode();
            }
        });

        //显示播放列表
        mPlayListBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.showAtLocation(v,Gravity.BOTTOM,0,0);
                mEnterAnimator.start();

            }
        });

        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mExitAnimator.start();
            }
        });

        mPopupWindow.setonPlayListItemClickListener(new PlayList_PopupWindow.onPlayListItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.playByIndex(position);
                }
            }
        });

        //playMode onClick
        mPopupWindow.setPlayListActionListener(new PlayList_PopupWindow.PlayListActionListener() {
            @Override
            public void onPlayModeClick() {
                switchPlayMode();
            }

            @Override
            public void onPlayOrderClick() {
                Constants.isOrder = !Constants.isOrder;
                //Toast.makeText(PlayerActivity.this, "switch play order", Toast.LENGTH_LONG).show();
                mPlayerPresenter.reversePlayList();
                mPopupWindow.updatePlayListOrderView(Constants.isOrder );
            }
        });

    }

    private void switchPlayMode() {
        XmPlayListControl.PlayMode playMode = sPlayModeRule.get(Constants.CURRENT_MODE);
        //修改播放模式
        if (mPlayerPresenter != null) {
            mPlayerPresenter.switchPlayMode(playMode);
        }
    }

    private void updateBGAlpha(float alpha) {
        Window window = getWindow();
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.alpha = alpha;
        window.setAttributes(attributes);
    }

    /**
     * 根据状态更新播放图标
     */
    private void updatePlayModeBtnImg() {
        int resID = R.drawable.selector_play_mode_list_order;
        switch (Constants.CURRENT_MODE){
            case PLAY_MODEL_LIST:
                resID = R.drawable.selector_play_mode_list_order;
                break;
            case PLAY_MODEL_RANDOM:
                resID = R.drawable.selector_play_mode_random;
                break;
            case PLAY_MODEL_LIST_LOOP:
                resID = R.drawable.selector_play_mode_list_order_loop;
                break;
            case PLAY_MODEL_SINGLE_LOOP:
                resID = R.drawable.selector_play_mode_single_loop;
                break;
        }

        mPlayModeSwitchBtn.setImageResource(resID);
    }


    private void initView() {
        mControlBtn = this.findViewById(R.id.play_or_pause_btn);
        mDuration = this.findViewById(R.id.track_duration);
        mCurrentPos = this.findViewById(R.id.current_position);
        mDurationBar = this.findViewById(R.id.track_seek_bar);
        mPlayPreBtn = this.findViewById(R.id.play_pre);
        mPlayNextBtn = this.findViewById(R.id.play_next);
        mTrackTitleTv = this.findViewById(R.id.track_title);

        if (!TextUtils.isEmpty(mTrackTitleText)) {
            mTrackTitleTv.setText(mTrackTitleText);
        }

        mTrackPageView = this.findViewById(R.id.track_pager_view);
        //设置适配器
        mPlayerTrackPagerAdapter = new PlayerTrackPagerAdapter();
        mTrackPageView.setAdapter(mPlayerTrackPagerAdapter);
        mTrackPageView.setOffscreenPageLimit(2);


        //切换播放模式的控件
        mPlayModeSwitchBtn = this.findViewById(R.id.player_mode_switch_btn);

        //显示播放列表的控件
        mPlayListBtn = this.findViewById(R.id.player_list);
        mPopupWindow = new PlayList_PopupWindow();

    }

    @Override
    public void onPlayStart() {
        //在播放开始时，切换播放按钮
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.drawable.selector_player_pause);
        }
    }

    @Override
    public void onPlayPause() {
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.drawable.selector_player_play);
        }
    }

    @Override
    public void onPlayCompleted() {

    }

    @Override
    public void onPlayStop() {
        mControlBtn.setImageResource(R.drawable.selector_player_play);
    }

    @Override
    public void onPlayError() {

    }

    @Override
    public void onNextPlay(Track track) {

    }

    @Override
    public void onPrePlay(Track track) {

    }

    @Override
    public void onListLoaded(List<Track> list) {
        //获取到播放列表，设置到适配器中去
        if (mPlayerTrackPagerAdapter != null) {
            mPlayerTrackPagerAdapter.setData(list);
        }

        if (mPopupWindow != null) {
            mPopupWindow.setListData(list);
        }


    }

    @Override
    public void onPlayModeChange(XmPlayListControl.PlayMode playMode) {
        //更新UI
        Constants.CURRENT_MODE = playMode;
        mPopupWindow.updatePlayModeView(playMode);
        updatePlayModeBtnImg();
        LogUtils.d(TAG, "-->registerViewCallback wymann + 1");
    }

    @Override
    public void onProgressChange(int currentProgress, int total) {

        //更新总事件、进度条
        String duration;
        String currentTime;
        if (total > 1000*60*60) { //用时分秒的格式
            duration = mHourFormat.format(total);
            currentTime = mHourFormat.format(currentProgress);
        }else {
            duration = mMinFormat.format(total);
            currentTime = mMinFormat.format(currentProgress);
        }
        //更新
        if (mDuration != null) {
            mDuration.setText(duration);
        }
        if (mCurrentPos != null) {
            mCurrentPos.setText(currentTime);
        }

        //根据当前播放进度更新
        if(mDurationBar != null && !mIsUserTouchProgressBar){
            mDurationBar.setMax(total);
            mDurationBar.setProgress(currentProgress);
        }
    }

    @Override
    public void onAdLoading() {

    }

    @Override
    public void onAdFinished() {

    }

    @Override
    public void onTrackUpdate(Track track,int playIndex) {
        if(track == null){
            LogUtils.d(TAG,"onTrackUpdate -->null");
            return;
        }
        this.mTrackTitleText = track.getTrackTitle();
        if (mTrackTitleTv != null) {
            mTrackTitleTv.setText(track.getTrackTitle());
        }

        //节目改变时，修改图片
        if(mTrackPageView != null) {
            mTrackPageView.setCurrentItem(playIndex, true);
        }

        //change the playing item in playlist
        if (mPopupWindow != null) {
            mPopupWindow.setCurrentPlayPosition(playIndex);
        }

    }

    //==========图片滑动时，切换播放节目===========================

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        /*if (mPlayerPresenter != null && mIsUserSlidePager) {
            mPlayerPresenter.playByIndex(position);
        }
        mIsUserSlidePager = false;*/
        if (mPlayerPresenter != null) {
            mPlayerPresenter.playByIndex(position);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
